import './style.scss'
import React, { useState, useEffect } from 'react'
import type { FC } from 'react'
// 如果在使用时有报错，建议安装一下 yarn add @ant-design/icons
import {
  DesktopOutlined,
  ExclamationCircleFilled,
  PieChartOutlined,
  TeamOutlined,
  UserOutlined
} from '@ant-design/icons'
import type { MenuProps } from 'antd'
import { Breadcrumb, Layout, Menu, theme, Modal } from 'antd'
import { useAppDispatch, useAppSelector } from '@/store/hooks'
import { userLogoutReducer, setBtns } from '@/reducers/user'
import { useNavigate, Navigate, Outlet, useLocation } from 'react-router-dom'
import routes from '@/router/routes'
import { getMenuAuthsApi } from '@/services/roleApi'

const { Header, Content, Footer, Sider } = Layout
const { confirm } = Modal

// const menuItems: MenuProps['items'] = [
//   {
//     label: '后台信息',
//     icon: <DesktopOutlined />,
//     key: '/info',
//     children: [
//       {
//         label: '图形汇总',
//         icon: <PieChartOutlined />,
//         key: '/info/dashoard'
//       }
//     ]
//   },
//   {
//     label: '电影管理',
//     icon: <PieChartOutlined />,
//     key: '/film',
//     children: [
//       {
//         label: '电影列表',
//         key: '/film/list'
//       },
//       {
//         label: '新增电影',
//         key: '/film/add'
//       }
//     ]
//   },
//   {
//     label: '后台设置',
//     icon: <TeamOutlined />,
//     key: '/sys',
//     children: [
//       {
//         label: '用户管理',
//         icon: <UserOutlined />,
//         key: '/sys/user'
//       },
//       {
//         label: '角色管理',
//         icon: <UserOutlined />,
//         key: '/sys/role'
//       },
//       {
//         label: '权限管理',
//         icon: <UserOutlined />,
//         key: '/sys/auth'
//       }
//     ]
//   }
// ]

const Admin: FC = () => {
  const navigate = useNavigate()
  const location = useLocation()
  const dispatch = useAppDispatch()
  const [menuItems, setMenuItems] = useState<MenuProps['items']>([])
  const token = useAppSelector((state) => state.user.userinfo.token)
  // 登录成功后得到它的角色id
  const roleid = useAppSelector((state) => state.user.userinfo.roleid)
  const [collapsed, setCollapsed] = useState(false)
  // 针对于菜单展开state数据使用了回调函数的方式来初始化数据
  const [menuSelectedKeys, setMenuSelectedKeys] = useState(() => {
    return [location.pathname]
  })
  const [menuOpenKeys, setMenuOpenKeys] = useState(() => {
    return ['/' + location.pathname.split('/')[1]]
  })

  // 根据角色id返回它所能拥有的菜单权限
  useEffect(() => {
    getMenuAuthsApi(roleid).then((res: any) => {
      setMenuItems(res.data.menus)
      dispatch(setBtns(res.data.btns))
    })
  }, [])

  // -- if下面不要写hook
  // 如果当前访问者没有登录则跳转到登录页面
  if (!token) {
    return <Navigate to="/login" />
  }

  const routeData = routes.find((route) => {
    return route.path == location.pathname.slice(1)
  })
  const breadcrumb: any = routeData ? routeData.meta.breadcrumb : []

  // 用户退出
  const userLogout = () => {
    confirm({
      title: '用户退出登录确认?',
      icon: <ExclamationCircleFilled />,
      content: '您真的要退出本次登录吗?',
      okText: '确认退出',
      cancelText: '考虑一下',
      onOk() {
        // 通知redux中的state数据要清空
        dispatch(userLogoutReducer())
        // 路由跳转
        // navigate('/login', { replace: true })
        // 为了安全,建议还是用window.location来进行刷新跳转
        window.location.href = '/login'
      },
      onCancel() {}
    })
  }

  return (
    <Layout className="admin-layout">
      <Sider
        collapsible
        collapsed={collapsed}
        onCollapse={(value) => setCollapsed(value)}
      >
        {/* 后台logo图片位置 */}
        <div className="admin-logo-vertical"></div>
        {/* 后台左侧菜单 */}
        <Menu
          theme="dark"
          defaultOpenKeys={menuOpenKeys}
          defaultSelectedKeys={menuSelectedKeys}
          mode="inline"
          onClick={({ key }) => {
            navigate(key, { replace: true })
          }}
          items={menuItems}
        />
      </Sider>
      <Layout>
        {/* 后台顶部导航 */}
        <Header className="admin-header-box">
          <div></div>
          <div>
            <span>张三</span>
            <span onClick={userLogout}>退出登录</span>
          </div>
        </Header>
        <Content style={{ margin: '0 16px' }}>
          {/* 面包屑导航 */}
          <Breadcrumb items={breadcrumb} />
          <div className="main-box">
            {/* 子路由挂载点 */}
            <Outlet />
          </div>
        </Content>
      </Layout>
    </Layout>
  )
}

export default Admin
